package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Dto.DishDto;
import com.itheima.reggie.Dto.SetmealDto;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.ResultContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Yan
 * @date 2022/2/26
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Override
    @Transactional
    public Result<String> addSetmeal(SetmealDto setmealDto) {
        if (ObjectUtils.isEmpty(setmealDto)){
            return Result.error("数据错误");
        }

        //2. 核心逻辑：数据封装保存到两种表：setmeal 套餐表，setmeal套餐菜品表

        //2.1套餐数据 剥离出来 保存到套餐表

        Setmeal setmeal =new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);

        this.saveOrUpdate(setmeal);

        //2.2 套餐菜品 数据剥离 保存到 套餐菜品表

        List<SetmealDish> setmealDishes =setmealDto.getSetmealDishes();

        List<SetmealDish> result =new ArrayList<>();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmeal.getId());
            result.add(setmealDish);
        }

        setmealDishService.saveBatch(result);

        return Result.success("添加成功");
    }

    @Override
    public Result<Page<SetmealDto>> findSetmealByPage(Long page, Long pageSize, String name) {

        //参数校验
        if (ObjectUtils.isEmpty(page)||page<=0){
            page=1L;
        }
        if (ObjectUtils.isEmpty(pageSize)||pageSize<=0){
            pageSize=10L;
        }

        Page<Setmeal> setmealPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Setmeal> wrapper =new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.isNotBlank(name),Setmeal::getName,name);

        wrapper.orderByDesc(Setmeal::getUpdateTime);

        this.page(setmealPage, wrapper);


        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> setmealDtos =new ArrayList<>();

        for (Setmeal record : records) {
            SetmealDto setmealDto =new SetmealDto();

            BeanUtils.copyProperties(record,setmealDto);

            Long categoryId = record.getCategoryId();
            //根据分类id查询分类名称
            Category category = categoryService.getById(categoryId);


            setmealDto.setCategoryName(category.getName());

            setmealDtos.add(setmealDto);


        }
        //数据封装
        Page<SetmealDto> setmealDtoPage =new Page<>();

        BeanUtils.copyProperties(setmealPage,setmealDtoPage);

        setmealDtoPage.setRecords(setmealDtos);

        return Result.success(setmealDtoPage);
    }

    @Override
    @Transactional
    public Result<String> deleteSetmeal(List<Long> ids) {
        if (ObjectUtils.isEmpty(ids)){
            return Result.error("数据错误");
        }

        //2. 删除逻辑：起售不能删除
        //2.1 根据条件删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();

        wrapper.in(Setmeal::getId,ids);
        List<Setmeal> list = this.list(wrapper);

        //可以被删除的套餐id
        List<Long> delIds =new ArrayList<>();
        //List<Long> notDelIds = new ArrayList<>();

        for (Setmeal setmeal : list) {
            if (setmeal.getStatus()!=1){
                delIds.add(setmeal.getId());
            }
        }
        if (delIds.isEmpty()){
            return Result.error("删除失败");
        }
        //2.2删除套餐
        this.removeByIds(delIds);


        LambdaQueryWrapper<SetmealDish> wrapper1 =new LambdaQueryWrapper<>();

        wrapper1.in(SetmealDish::getSetmealId,delIds);

        setmealDishService.remove(wrapper1);

        //List<SetmealDish> list = setmealDishService.list(wrapper1);

        //List<Long> setmealDishIds = list.stream().map(setmealDish -> setmealDish.getId()).collect(Collectors.toList());

        //setmealDishService.removeByIds(setmealDishIds);



        //this.removeByIds(ids);
        /*List<String> notDelNeme =new ArrayList<>();
        if (notDelIds.size()> 0){
            LambdaQueryWrapper<Setmeal> wrapper2 =new LambdaQueryWrapper<>();
            wrapper2.in(Setmeal::getId,notDelIds);
            List<Setmeal> notDelList = this.list(wrapper2);
            for (Setmeal setmeal : notDelList) {
                notDelNeme.add(setmeal.getName());
            }
            return Result.success("删除成功"+notDelNeme.toString()+"正在起售不能删除");
        }*/
        return Result.success("删除成功");
    }

    @Override
    public Result<String> status(Integer status, List<Long> ids) {
        if (ObjectUtils.isEmpty(status)||ObjectUtils.isEmpty(ids)){
            return Result.error("数据错误");
        }


        List<Setmeal> setmeals = this.listByIds(ids);

        setmeals = setmeals.stream().map(setmeal -> {
            setmeal.setStatus(status);
            return setmeal;

        }).collect(Collectors.toList());


        this.saveOrUpdateBatch(setmeals);


        return Result.success("修改成功");
    }

    @Override
    public Result<SetmealDto> findSetmealById(Long id) {
        if (ObjectUtils.isEmpty(id)){
            return Result.error("数据错误");
        }

        LambdaQueryWrapper<Setmeal> setmealWrapper =new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getId,id);
        Setmeal dbSetmeal = this.getOne(setmealWrapper);

        SetmealDto setmealDto =new SetmealDto();

        BeanUtils.copyProperties(dbSetmeal,setmealDto);

        LambdaQueryWrapper<SetmealDish> setmealDishWrapper =new LambdaQueryWrapper<>();

        setmealDishWrapper.eq(SetmealDish::getSetmealId,dbSetmeal.getId());
        List<SetmealDish> list = setmealDishService.list(setmealDishWrapper);

        setmealDto.setSetmealDishes(list);

        return Result.success(setmealDto);
    }

    @Override
    @Transactional
    public Result<String> updateSetmeal(SetmealDto setmealDto) {
        if (ObjectUtils.isEmpty(setmealDto)){
            return Result.error("数据错误");
        }

        Setmeal setmeal =new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        this.saveOrUpdate(setmeal);



        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //先删后增
        LambdaQueryWrapper<SetmealDish> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(wrapper);

        setmealDishes=setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            return setmealDish;
        }).collect(Collectors.toList());

        setmealDishService.saveOrUpdateBatch(setmealDishes);

        return Result.success("修改成功");
    }

    @Override
    public Result<List<Setmeal>> setmealList(Long categoryId,Integer status) {
        //业务逻辑：根据套餐分类id查询套餐，只查询在售状态的套餐
        LambdaQueryWrapper<Setmeal> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotEmpty(categoryId),Setmeal::getCategoryId,categoryId).
                eq(ObjectUtils.isNotEmpty(status),Setmeal::getStatus,status).
                orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = this.list(wrapper);

        return Result.success(list);
    }

    @Override
    public Result<List<DishDto>> getSetmealDishList(Long setmealId) {
        if (ObjectUtils.isEmpty(setmealId)){
            return Result.error("数据错误");
        }

        //2.业务逻辑
        LambdaQueryWrapper<SetmealDish> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish> list = setmealDishService.list(wrapper);




        List<Long> dishIds = list.stream().map(SetmealDish::getDishId).collect(Collectors.toList());

        if (dishIds.size() == 0){
            return Result.error("该套餐里没有菜品");
        }

        LambdaQueryWrapper<Dish> wrapper1 =new LambdaQueryWrapper<>();
        wrapper1.in(Dish::getId,dishIds);

        List<Dish> dishList = dishService.list(wrapper1);
        List<DishDto> dishDtos =new ArrayList<>();

        for (Dish dish : dishList) {
            DishDto dishDto =new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            dishDtos.add(dishDto);
        }

        for (SetmealDish setmealDish : list) {
            for (DishDto dishDto : dishDtos) {
                if (setmealDish.getDishId().equals(dishDto.getId())){
                    dishDto.setCopies(setmealDish.getCopies());
                }
            }
        }

        //dishDtos.stream().collect(Collectors.toMap())



        return Result.success(dishDtos);
    }
}
